<template>
  <div>
    <ul class="item-list">
      <li class="item"
          v-for="(item,key) of letters"
          :ref="item"
          :key="item"
          @click="handlerLetterClick"
          @touchstart.prevent="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
      >{{item}}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "alphabet",
    props: {
      cities: Object
    },
    data(){
      return {
        touchStatus: false,
        startY : 0,
        timer:null
      }
    },
    computed:{
      //  定义一个包含字母表的数组
      letters(){
        const letters = []
        for(let i in this.cities){
          letters.push(i)
        }
        return letters
      }
    },
    updated(){
      this.startY = this.$refs['A'][0].offsetTop
    },
    methods: {
      handlerLetterClick(e) {
        this.$emit('change',e.target.innerText)
      },
      //  触摸时状态为true
      handleTouchStart(){
        this.touchStatus = true
      },
      //  触摸结束，把状态改回false
      handleTouchEnd(){
        this.touchStatus = false
      },
      //  触摸时处理机制
      handleTouchMove(e){
        if(this.touchStatus =  true){
            //  取字母A距搜索框的距离
          if(this.timer){
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(() => {

            const touchY = e.touches[0].clientY
            //  判断当前被触摸的字母在字母表的第几个位置
            const index = Math.floor((touchY - this.startY - 79 )/ 20 )
            if(index >= 0 && index < this.letters.length){
              //  把被触摸的字母传给change
              this.$emit('change',this.letters[index])
            }
          },16)

        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varible.styl"
  .item-list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    right: 0
    top: 1.58rem
    bottom: 0
    width: .4rem

    .item
      text-align: center
      line-height: .4rem
      color: $bgColor
</style>
